package com.mall.mina.config;

import com.mall.mina.util.AgreementConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.nio.charset.Charset;

/**
 * describe 自定义解码器
 */
@Slf4j
public class CustomProtocolDecoder extends CumulativeProtocolDecoder {

    private final Charset charset;

    public CustomProtocolDecoder() {
        this.charset = Charset.defaultCharset();
    }

    // 构造方法注入编码格式
    public CustomProtocolDecoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        CustomPack pack = new CustomPack();
        int readLen = in.remaining();
        final int LEN = 4;
        if (readLen >= LEN) {
            in.mark();
            byte[] LenArray = new byte[2];
            in.get(LenArray);
            pack.setLen(LenArray);

            byte[] contentArray = new byte[readLen - 4];
            in.get(contentArray);
            pack.setContent(contentArray);

            //指纹总长度526 无指纹数据长度为14
            if(contentArray[0] == AgreementConstant.FINGERPRINT_GET && readLen<500 && readLen!=14){
                in.reset();
                return false;
            }

            byte[] crcArray = new byte[2];
            in.get(crcArray);
            pack.setCrc(crcArray);
            out.write(pack);
            return in.remaining() > 0;
        }
        return false;
    }
}